/*******************************************************************************
 * Copyright (c) 2005, 2007 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package us.gaaoc.framework.dao;

import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;

import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.CourtEvents;
import us.gaaoc.framework.model.events.court.CourtEventsExtendedData;
import us.gaaoc.framework.model.events.court.CourtEventsExtendedType;

/**
 * 
 * @author hea
 * @date Apr 25, 2006
 * @version: GAJE 1.5
 * 
 */
public class CourtEventsDAOHibernate extends
		GenericHibernateDAO<CourtEvents, String, CourtEventsDAO> implements
		CourtEventsDAO {

	private Logger LOG = Logger.getLogger(CourtEventsDAOHibernate.class);

	protected CourtEventsDAOHibernate() {

	}

	public void updateCourtDate(String caseRecordUuid, Date courtDate,
			String personUuid) {
		try {
			Query q = this
					.getSession()
					.createQuery(
							"from CourtEvents events where events.caseRecord.uuid = ? and events.eventType.code = 1 "
									+ "order by events.eventTime desc limit 0,1");
			q.setString(0, caseRecordUuid);
			List l = q.list();
			CourtEvents courtEvents = new CourtEvents();
			// If a prior Court Date exists, then update it, . . .
			if (!l.isEmpty()) {
				courtEvents = (CourtEvents) l.get(0);
				if (courtEvents != null) {
					courtEvents.setEventTime(courtDate);
					this.makePersistent(courtEvents);
				}
			} else {
				// else, if no prior Court Date exist, then create a new entry.
				String insertSQL = "INSERT INTO courtEvents VALUES (?, 1 , ?, ?, ?)";
				SQLQuery q2 = this.getSession().createSQLQuery(insertSQL);
				// UUID
				String courtEventUuid = UUID.randomUUID().toString();
				q2.setString(0, courtEventUuid);
				// Event Date Time
				q2.setTimestamp(1, courtDate);
				// Case Record UUID
				q2.setString(2, caseRecordUuid);
				// Person UUID
				q2.setString(3, personUuid);

				// Execute the insert statement
				q2.executeUpdate();
			}
		} catch (HibernateException sqle) {
			LOG.debug("\nError updating the Court Date!\n");
			sqle.printStackTrace();
		}
	}

	public Date findCourtDate(String caseRecordUuid) {
		/*
		 * Query q = this .getSession() .createQuery( "from CourtEvents events
		 * where events.caseRecord.uuid = ? and events.eventType.code = 1");
		 * 
		 * CourtEvents courtEvents = (CourtEvents) q.uniqueResult(); if
		 * (courtEvents != null) return courtEvents.getEventTime(); else return
		 * null;
		 */
		String sql = "select MAX(events.eventTime) "
				+ "from CourtEvents events where events.caseRecord.uuid = ? "
				+ "and events.eventType.code = 1";
		Query q = this.getSession().createQuery(sql);
		q.setString(0, caseRecordUuid);
		Date date = (Date) q.uniqueResult();
		if (date != null)
			return date;
		else
			return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see us.gaaoc.framework.dao.CourtEventsDAO#deleteCourtEvent(us.gaaoc.framework.model.CaseRecord)
	 */
	public void deleteCourtEvent(CaseRecord record) {
		String hqlDelete = "delete CourtEvents ce WHERE ce.caseRecord.uuid=?";

		int deletedEntities = this.getSession().createQuery(hqlDelete)
				.setString(0, record.getUuid()).executeUpdate();
		LOG.info("deleted rows " + deletedEntities);

	}

	@Override
	public void updateCourtDateExtendedData(String caseRecordUuid,
			int dataID, String value) {
		try {
			
			Date courtDate = new Date();
			Query q = this
					.getSession()
					.createQuery(
							"from CourtEvents events where events.caseRecord.uuid = ? and events.eventType.code = 1 "
									+ "order by events.eventTime desc limit 0,1");
			q.setString(0, caseRecordUuid);
			List l = q.list();
			CourtEvents courtEvents = null;
			if (!l.isEmpty()) {
				courtEvents = (CourtEvents) l.get(0);
				//courtEvents = (CourtEvents) this.getSession().merge(courtEvents);
				LOG.debug(
						DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.ENGLISH).format(courtEvents.getEventTime()));
				if (courtEvents != null) {
					
					Query q2 = this
						.getSession().createQuery(
							"from CourtEventsExtendedData ev where ev.courtEvent.uuid = ? and ev.type.id = ?");
					q2.setParameter(0, courtEvents.getUuid());
					q2.setInteger(1,dataID);

					List lext = q2.list();
					if(!lext.isEmpty()) {
						CourtEventsExtendedData extendedData = (CourtEventsExtendedData) q2.list().get(0);
						extendedData.setValue(value);												
						this.getSession().save(extendedData);
					}else{
						CourtEventsExtendedData extendedData = new CourtEventsExtendedData();
						extendedData.setCourtEvent(courtEvents);
						extendedData.setType(new CourtEventsExtendedType(dataID));
						extendedData.setValue(value);
						this.getSession().save(extendedData);
					}
					
				}
			}
		} catch (HibernateException sqle) {
			LOG.debug("\nError updating the Court Date Extended Data!\n");
			sqle.printStackTrace();
		}
	}

}
